package com.liber.sun.controller;

import com.alibaba.fastjson.JSONObject;
import com.liber.sun.support.Result;
import com.liber.sun.utils.MyFileUtils;
import com.liber.sun.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by sunlingzhi on 2017/10/22.
 */
@RestController //默认返回json格式
@RequestMapping("/fileManager")
public class FileManagerController {

    @Value("${web.upload-path}filemanager/")
    private String ROOT;
    /**
     *  展示文件
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result listFile(@RequestParam("path") String path, @RequestParam("username") String username) {
        // 返回的结果集
        List<JSONObject> fileItems = new ArrayList<>();
        try {
            DirectoryStream<Path> directoryStream= Files.newDirectoryStream(Paths.get(ROOT+username+"/",path));
            String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
            SimpleDateFormat dt = new SimpleDateFormat(DATE_FORMAT);
            for (Path pathObj:directoryStream){
                // 获取文件基本属性
                BasicFileAttributes attrs = Files.readAttributes(pathObj, BasicFileAttributes.class);

                // 封装返回JSON数据
                JSONObject fileItem = new JSONObject();
                fileItem.put("name", pathObj.getFileName().toString());
                fileItem.put("date", dt.format(new Date(attrs.lastModifiedTime().toMillis())));
                fileItem.put("size", attrs.size());
                fileItem.put("type", attrs.isDirectory() ? "folder" : "file");
                fileItems.add(fileItem);
            }
            return ResultUtil.success(fileItems);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 单文件上传
     */
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public Result<String> uploadSingle(@RequestParam("file") MultipartFile file,
                                       @RequestParam("destination") String destination,
                                       @RequestParam("username") String username) {
        String path = ROOT+username+"/" + destination;
        if (!file.isEmpty()) {
            try {
                InputStream is = file.getInputStream();
                MyFileUtils.writeInputStreamToFile(is, new File(path + file.getOriginalFilename()));
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }
            return ResultUtil.success(file.getOriginalFilename());
        } else {
            return ResultUtil.error(-1, "文件为空");
        }
    }



    @RequestMapping(value = "/rename", method = RequestMethod.GET)
    public Result<String> rename(@RequestParam("newPath") String newPath,
                            @RequestParam("path") String path,@RequestParam("username") String username) throws IOException {
        File srcFile = new File(ROOT+username+"/", path);
        File destFile = new File(ROOT+username+"/", newPath);
        if (srcFile.isFile()) {
            MyFileUtils.moveFile(srcFile, destFile);
        } else {
            MyFileUtils.moveDirectory(srcFile, destFile);
        }
        return ResultUtil.success("重命名，成功");
    }

    @RequestMapping(value = "/remove", method = RequestMethod.GET)
    public Result<String> remove( @RequestParam("path") String path,
                                  @RequestParam("type") String type,@RequestParam("username") String username) throws Exception {
        if(type.equals("file")){
            File srcFile = new File(ROOT+username+"/", path);
            MyFileUtils.deleteFile(srcFile);
        }else if(type.equals("folder")){
            MyFileUtils.deleteFiles(ROOT+username+"/"+path,false);
        }
        return ResultUtil.success("删除成功");
    }

    @RequestMapping(value = "/createFolder", method = RequestMethod.POST)
    public Result<String> createFolder(
                          @RequestParam("path") String path,@RequestParam("username") String username
                       ) throws IOException {
            File newDir = new File(ROOT+username+"/" + path);
            if(!newDir.mkdir()){
                return ResultUtil.error(-1,"不能创建目录："+path);
            }
            return  ResultUtil.success("目录创建成功："+path);
    }

    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public ResponseEntity<InputStreamResource> download( @RequestParam("path") String path,
                                                         @RequestParam("filename") String filename,@RequestParam("username") String username) throws Exception {

        try {
            File file = new File(ROOT+username+"/"+path , filename);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition", "attachment;filename=" + filename);
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");

            return ResponseEntity
                    .ok()
                    .headers(headers)
                    .contentLength(file.length())
                    .body(new InputStreamResource(MyFileUtils.getFileContentByInputStream(file)));
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

//     * 多文件上传 主要是使用了MultipartHttpServletRequest和MultipartFile
//     *
//     * @param request
//     * @return
//     */
//    @RequestMapping(value = "upload/multi", method = RequestMethod.POST)
//    public Result<String> uploadMulti(HttpServletRequest request,
//                                      @RequestParam("destination") String destination) {
//        String path = ROOT + destination;
//        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
//        MultipartFile file ;
//        for (int i = 0; i < files.size(); i++) {
//            file = files.get(i);
//            if (!file.isEmpty()) {
//                try {
//                    InputStream is = file.getInputStream();
//                    MyFileUtils.writeInputStreamToFile(is, new File(path + file.getOriginalFilename()));
//                } catch (Exception e) {
//                    throw new RuntimeException(e.getMessage());
//                }
//            } else {
//                return ResultUtil.error(-1, "文件" + i + "为空");
//            }
//        }
//        return ResultUtil.success("上传成功");
//
//    }
}
